package com.wanwu.channel.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @description:
 * @author: zhanghaixin
 * @date: 2020-05-09
 * @time: 21:06
 */
public class HostUtils {
    private static Logger logger = LoggerFactory.getLogger(HostUtils.class);

    private static String hostName = getSystemInfoByCommand(new String[] { "hostname" });
    private static String simpleName = getSimpleName(getHostName());

    public static String getHostName() {
        return hostName;
    }

    public static String getSimpleName() {
        return simpleName;
    }


    private static String getSystemInfoByCommand(String[] command) {
        String result = "";
        BufferedReader read = null;
        InputStream in = null;
        Process pro = null;
        try {
            pro = Runtime.getRuntime().exec(command);
            pro.waitFor();
            in = pro.getInputStream();
            read = new BufferedReader(new InputStreamReader(in));
            result = read.readLine();
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
        } finally {
            try {
                if (null != pro) {
                    pro.destroy();
                }
                if (null != read) {
                    read.close();
                }
                if (null != in) {
                    in.close();
                }
            } catch (Exception e) {
                logger.debug(e.getMessage(), e);
            }
        }
        return result;
    }

    private static String getSimpleName(String hostName) {
        if (StringUtils.isNotEmpty(hostName)) {
            int index = hostName.indexOf(".");
            if (index > 0) {
                hostName = hostName.substring(0, index);
            }
        }
        return hostName;
    }

}
